package com.zy.constraints;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;

/**
 * @author zhy
 * @date 2025/6/20 14:38
 */
public class PatternValidator implements ConstraintValidator<Pattern, String> {
    private java.util.regex.Pattern pattern;

    @Override
    public void initialize(Pattern constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        String regexp = constraintAnnotation.regexp();
        pattern = java.util.regex.Pattern.compile(regexp);
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isEmpty(s)) {
            return true;
        }
        Matcher matcher = pattern.matcher(s);
        return matcher.matches();
    }
}
